package platform.common.action.botovo;

import java.lang.reflect.Field;

import org.apache.commons.beanutils.BeanUtils;

import platform.common.action.botovo.BeanAnnotation;

/**
 *
 * @description <br/>
 *
 *
 * @createTime Jan 19, 2010 11:41:26 PM
 * @author wg
 *
 */
public class BeanUtil {

	/**
	 * @description
	 *
	 *
	 * @createTime Jan 19, 2010 11:43:25 PM
	 * @author wg
	 *
	 * @param target
	 * @param source
	 */
	public static void copyProperties(Object target, Object source) {
		Field[] fields = source.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			if (fields[i].isAnnotationPresent(BeanAnnotation.class)) {
				BeanAnnotation annotation = fields[i]
						.getAnnotation(BeanAnnotation.class);
				try {
					if (!"".equals(annotation.targetClass())) { // 判断是否设置了targetClass
						boolean isTarget = false;
						String[] clazzs = annotation.targetClass().split(","); // 如果设置了多个targetClass
						for (int j = 0; j < clazzs.length; j++) {
							if (clazzs[j].equals(target.getClass()
									.getSimpleName())) {
								isTarget = true;
								break;
							}
						}
						if (isTarget) {
							setProperty(target, annotation, source, fields[i]
									.getName());
						}
					} else {
						setProperty(target, annotation, source, fields[i]
								.getName());
					}
				} catch (Exception e) {
					System.out.println("错误：" + e.getMessage());
				}
			}
		}
	}

	/**
	 * @description
	 *
	 *
	 * @createTime Jan 20, 2010  12:13:40 AM
	 * @author wg
	 *
	 * @param target      目标
	 * @param annotation  注解
	 * @param source      源
	 * @param sourceName  源属性名
	 */
	private static void setProperty(Object target, BeanAnnotation annotation,
			Object source, String sourceName) {
		try {
			String[] obverseFields = annotation.obverseField().split(",");
			for (int i = 0; i < obverseFields.length; i++) {
				Field field = null;
				try{
					field = target.getClass().getDeclaredField(
							obverseFields[i]);
				}catch (Exception e) {
					System.out.println("消息：没有对应的"+e.getMessage());
				}
				if (field != null) {
					BeanUtils.setProperty(target, field.getName(), BeanUtils
							.getProperty(source, sourceName));
					break;
				}
			}
		} catch (Exception e) {
			System.out.println("错误：" + e.getMessage());
			e.printStackTrace();
		}
	}
}
